/*
实际渲染 Portal 内容的组件

主要功能：

  维护 portals 状态数组

  实现 mount/update/unmount 方法操作 portals

  使用绝对定位和 zIndex 确保内容显示在最上层

  渲染所有注册的 Portal 内容


*/
import React from 'react'
import {View, StyleSheet} from 'react-native'

export type State = {
  portals: Array<{
    key: number
    children: React.ReactNode
  }>
}
export type PortalManagerState = {
  portals: any[]
}

export default class PortalManager extends React.PureComponent<{}, PortalManagerState> {
  state: State = {
    portals: [],
  }

  mount = (key: number, children: React.ReactNode) => {
    this.setState(state => ({
      portals: [...state.portals, {key, children}],
    }))
  }

  update = (key: number, children: React.ReactNode) =>
    this.setState(state => ({
      portals: state.portals.map(item => {
        if (item.key === key) {
          return {...item, children}
        }
        return item
      }),
    }))

  unmount = (key: number) =>
    this.setState(state => ({
      portals: state.portals.filter(item => item.key !== key),
    }))

  render() {
    return this.state.portals.map(({key, children}, i) => (
      <View
        key={key}
        collapsable={false /* Need collapsable=false here to clip the elevations, otherwise they appear above sibling components */}
        pointerEvents="box-none"
        style={[StyleSheet.absoluteFill, {zIndex: 1000 + i}]}>
        {children}
      </View>
    ))
  }
}
